package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.PassToken;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.core.domain.Ztree;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.domain.entity.SysDictData;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.file.FileUploadUtils;
import com.xydtech.common.utils.file.MimeTypeUtils;
import com.xydtech.ecard.config.service.IEcardApiSysConfigService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.FivelevelAddr;
import com.xydtech.system.domain.SysConfig;
import com.xydtech.system.domain.SysPost;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用接口服务类
 *
 * @author yjs
 * @date 2022/7/28 10:22
 */

@Controller
@Api(tags = "电子名片-通用服务接口")
@RequestMapping("/ecardSaasApi/commonApi")
public class EcardApiCommonController extends EcardApiBaseController {
    @Autowired
    private IFivelevelAddrService fiveLevelAddrService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysWechatAppletService wechatAppletService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardApiSysConfigService ecardApiSysConfigService;

    @Value("${url.apiServiceUrl}")
    private String apiServiceUrl;

    /**
     * 查询行政区划信息
     *
     * @author yjs
     * @date 2022/7/28 10:09
     */
    @PassToken
    @GetMapping("/getAdministrativeDivision")
    @ApiOperation(value = "电子名片-获取行政区划信息", notes = "电子名片-获取行政区划信息")
    @ResponseBody
    public ResponseModel getAdministrativeDivision(@RequestParam(required = false) String proCode, @RequestParam(required = false) Long pLevel) {
        try {
            FivelevelAddr fivelevelAddr = new FivelevelAddr();
            fivelevelAddr.setUpCode(proCode);//上级编码
            fivelevelAddr.setpLevel(pLevel);//层级
            List<FivelevelAddr> list = fiveLevelAddrService.selectSysFivelevelAddrList(fivelevelAddr);
            return ResponseModel.ok(list);
        } catch (Exception ex) {
            return ResponseModel.error("数据异常，请刷新后重试！");
        }
    }

    /**
     * 查询字典表数据
     *
     * @author yjs
     * @date 2022/7/28 10:09
     */
    @PassToken
    @GetMapping("/getDictionaryInfo")
    @ApiOperation(value = "电子名片-获取字典表数据", notes = "电子名片-获取字典表数据")
    @ResponseBody
    public ResponseModel getDictionaryInfo(@RequestParam(required = false) String dictType) {
        try {
            String salt = getSalt();//盐值
            if (StringUtils.isEmpty(dictType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            String currentUserId = getCurrentUserId();
            List<SysDictData> list = new ArrayList<>();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            if (userInfo != null) {
                //当前小程序id
                SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
                //当前小程序对应的法人机构ID
                Long parentDeptId = wechatApplet.getDeptId();
                SysDictData dict = new SysDictData();
                dict.setDictType(dictType);
                dict.setDeptId(parentDeptId);
                dict.setStatus("0");
                list = dictDataService.selectDictDataList(dict);
            }
            return ResponseModel.ok(list);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("获取字典数据失败");
        }
    }

    /**
     * 京东地图逆解析获取地理位置信息
     *
     * @author yjs
     * @date 2022/7/28 10:48
     */
    @GetMapping(value = "/getCoordinatePositionInfo")
    @ApiOperation(value = "电子名片-京东地图逆解析获取地理位置信息", notes = "电子名片-京东地图逆解析获取地理位置信息")
    @ApiImplicitParam(name = "coordinate", value = "经纬度", dataType = "String", dataTypeClass = String.class, paramType = "query", required = true)
    @ResponseBody
    public ResponseModel getCoordinatePositionInfo(@RequestParam(required = false) String coordinate) {
        try {
            if (StringUtils.isEmpty(coordinate)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            RestTemplate restTemplate = new RestTemplate();
            //调用京东地址获取地理位置，改为bigdata请求
            String apiUrl = apiServiceUrl + "/api/requestJdMap/getLocation?coordinate=" + coordinate;
            HttpMethod method = HttpMethod.POST;
            JSONObject jsonObject = new JSONObject();
            //2、添加请求头
            HttpHeaders headers = new HttpHeaders();
            //执行HTTP请求，将返回的结构使用ResultVO类格式化
            HttpEntity<String> requestEntity = new HttpEntity<String>(JSON.toJSONString(jsonObject), headers);
            ResponseEntity response = restTemplate.exchange(apiUrl, method, requestEntity, String.class);
            JSONObject body = JSON.parseObject(String.valueOf(response.getBody()));
            String code = body.getString("code");
            JSONObject data = JSON.parseObject(body.getString("data"));
            if ("100".equals(code)) {
                return ResponseModel.ok(data);
            }else {
                return ResponseModel.error("获取地理位置名称失败！");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("获取地理位置失败");
        }
    }

    /**
     * 查询岗位数据
     *
     * @author yjs
     * @date 2022/11/25 15:07
     */
    @PassToken
    @GetMapping("/getPostList")
    @ApiOperation(value = "电子名片-获取岗位列表", notes = "电子名片-获取岗位列表")
    @ResponseBody
    public ResponseModel getPostList() {
        try {
            List<SysPost> list = postService.selectPostAll();
            return ResponseModel.ok(list);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("获取岗位列表失败");
        }
    }

    /**
     * 根据法人机构ID查询机构数据
     *
     * @author yjs
     * @date 2022/11/25 15:07
     */
    @PassToken
    @GetMapping("/getOrgList")
    @ApiOperation(value = "电子名片-根据法人机构ID获取机构列表", notes = "电子名片-根据法人机构ID获取机构列表")
    @ResponseBody
    public ResponseModel getOrgList() {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            String appId = wechatApplet.getAppid();
            if (StringUtils.isEmpty(appId)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            //查询法人机构
            SysDept dept = new SysDept();
            dept.setParentId(wechatApplet.getDeptId());
            List<SysDept> sysDepts = sysDeptService.selectDeptList(dept, salt);
            sysDepts.add(sysDeptService.selectDeptById(wechatApplet.getDeptId(), salt));
            List<Ztree> ztrees = sysDeptService.initZtree(sysDepts);
            return ResponseModel.ok(ztrees);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("获取机构列表失败");
        }
    }

    /**
     * 电子名片-图片上传并添加水印
     *
     * @param:watermark 水印内容
     * @param:fileName 文件保存路径
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/imageUploadAddWatermark")
    @ApiOperation(value = "电子名片-图片上传并添加水印", notes = "电子名片-图片上传并添加水印")
    @ResponseBody
    public ResponseModel imageUploadAddWatermark(String watermark, String coordinate, String fileName,
                                                 @RequestParam("imgfile") MultipartFile imgfile) {
        try {
            if (StringUtils.isEmpty(watermark) || StringUtils.isEmpty(fileName)|| StringUtils.isEmpty(coordinate)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            String salt = getSalt();//盐值
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //图片验证
            if (!imgfile.isEmpty()) {
                FileUploadUtils.uploadCheckType(imgfile, MimeTypeUtils.IMAGE_EXTENSION);
                String imgUrl = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/" + userInfo.getUserId() + "/" + fileName + "/" + imgfile.getOriginalFilename();
                logger.info("文件路径========" + imgUrl);
                File file = new File(imgUrl);
                if (!file.getParentFile().exists()) {
                    //创建上级目录
                    file.getParentFile().mkdirs();
                }
                //图片添加水印后保存
                addWaterMask(imgfile, imgUrl, watermark, coordinate, userInfo.getUserName(), userInfo.getDeptName());
                return ResponseModel.ok(imgUrl.replaceAll(XydtechBusiPlatConfig.getProfile(), "/profile"));
            } else {
                return ResponseModel.error("图片不能为空！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("图片上传失败");
        }
    }
    /**
     * 电子名片-图片上传
     *
     * @param:fileName 文件名称
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/imageUpload")
    @ApiOperation(value = "电子名片-图片上传", notes = "电子名片-图片上传")
    @ResponseBody
    public ResponseModel imageUpload(String fileName, @RequestParam("imgfile") MultipartFile imgfile) {
        try {
            if ( StringUtils.isEmpty(fileName)) {
                return ResponseModel.error(ResultStatus.PARAMETER_ERROR);
            }
            String salt = getSalt();//盐值
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //图片验证
            if (!imgfile.isEmpty()) {
                FileUploadUtils.uploadCheckType(imgfile, MimeTypeUtils.IMAGE_EXTENSION);
                String imgUrl = XydtechBusiPlatConfig.getEcardFilePath() + "/" + userInfo.getDeptId() + "/" + userInfo.getUserId() + "/" + fileName ;
                // 上传并返回新文件名称
                String fileUrl = FileUploadUtils.upload(imgUrl, imgfile, false);
                return ResponseModel.ok(fileUrl);
            } else {
                return ResponseModel.error("图片不能为空！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("图片上传失败");
        }
    }

    /**
     * 电子名片-参数配置查询接口
     *
     * @return
     */
    @PassToken
    @GetMapping("/getSysConfigInfo")
    @ApiOperation(value = "电子名片-参数配置查询接口", notes = "电子名片-参数配置查询接口")
    @ResponseBody
    public ResponseModel getConfigInfo(@RequestParam(required = false) String configKey) {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        SysConfig config = new SysConfig();
        if (StringUtils.objIsNullOrEmpty(currentUserId)){
            config.setConfigKey(configKey);
            config.setDeptId(100L);
        } else {
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            if (StringUtils.isEmpty(configKey)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            config.setConfigKey(configKey);
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            config.setDeptId(sysDept.getDeptId());
        }
        SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);
        return ResponseModel.ok(sysConfig);
    }

    /**
     * 电子名片-根据商户类型和机构城乡类型查询参数配置
     *
     * @author yuzhiguo
     * @date 2024/8/22 下午4:47
     */
    @PostMapping(value = "/getConfigByMerchantType")
    @ApiOperation(value = "电子名片-根据商户类型和机构城乡类型查询参数配置", notes = "电子名片-根据商户类型和机构城乡类型查询参数配置")
    @ResponseBody
    public ResponseModel getConfigByMerchantType(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体

            if (StringUtils.objIsNullOrEmpty(currentUserId) || StringUtils.objIsNullOrEmpty(merchantType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            SysDept sysDept = sysDeptService.selectDeptById(userInfo.getDeptId(), salt);
            String urbanRuralType = sysDept.getUrbanRuralType();//城乡类型：1：城区、2：农区、3：城乡结合部
            String configKey = "";

            //判断
            switch (merchantType) {
                case "1": //个人
                    if ("1".equals(urbanRuralType)) {//城区
                        configKey = "ecard_urban_person_visit_days";
                    } else if ("2".equals(urbanRuralType)) {//农区
                        configKey = "ecard_agr_person_visit_days";
                    } else if ("3".equals(urbanRuralType)) {//城乡结合部
                        configKey = "ecard_joint_person_visit_days";
                    }
                    break;
                case "2": //商户
                    if ("1".equals(urbanRuralType)) {//城区
                        configKey = "ecard_urban_merchant_visit_days";
                    } else if ("2".equals(urbanRuralType)) {//农区
                        configKey = "ecard_agr_merchant_visit_days";
                    } else if ("3".equals(urbanRuralType)) {//城乡结合部
                        configKey = "ecard_joint_merchant_visit_days";
                    }
                    break;
                case "3": //企业
                    if ("1".equals(urbanRuralType)) {//城区
                        configKey = "ecard_urban_enterprise_visit_days";
                    } else if ("2".equals(urbanRuralType)) {//农区
                        configKey = "ecard_agr_enterprise_visit_days";
                    } else if ("3".equals(urbanRuralType)) {//城乡结合部
                        configKey = "ecard_joint_enterprise_visit_days";
                    }
                    break;
                case "4": //新型农业主体
                    if ("1".equals(urbanRuralType)) {//城区
                        configKey = "ecard_urban_agriculture_visit_days";
                    } else if ("2".equals(urbanRuralType)) {//农区
                        configKey = "ecard_agr_agriculture_visit_days";
                    } else if ("3".equals(urbanRuralType)) {//城乡结合部
                        configKey = "ecard_joint_agriculture_visit_days";
                    }
                    break;
            }
            SysConfig config = new SysConfig();
            config.setConfigKey(configKey);
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            config.setDeptId(dept.getDeptId());
            SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);
            return ResponseModel.ok(sysConfig);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

}
